package com.piggy.common.datasource.mybatisplus;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.piggy.common.satoken.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * MP注入处理器
 *
 * @author fanglei
 * @date 2021/05/28 14:24
 **/
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        //根据属性名字设置要填充的值
        if (metaObject.hasGetter("createTime")) {
            if (metaObject.getValue("createTime") == null) {
                this.setFieldValByName("createTime", new Date(), metaObject);
            }
        }
        if (metaObject.hasGetter("createBy")) {
            if (metaObject.getValue("createBy") == null) {
                String userName = ObjectUtil.isNull(SecurityUtils.getOauthUser()) ? null : SecurityUtils.getUsername();
                this.setFieldValByName("createBy", userName, metaObject);
            }
        }

        if (metaObject.hasGetter("creatorName")) {
            if (metaObject.getValue("creatorName") == null) {
                String userName = ObjectUtil.isNull(SecurityUtils.getOauthUser()) ? null : SecurityUtils.getUsername();
                this.setFieldValByName("creatorName", userName, metaObject);
            }
        }
        if (metaObject.hasGetter("creator")) {
            if (metaObject.getValue("creator") == null) {
                Long userId = ObjectUtil.isNull(SecurityUtils.getOauthUser()) ? null : SecurityUtils.getUserId();
                this.setFieldValByName("creator", userId, metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasGetter("updateBy")) {
            if (metaObject.getValue("updateBy") == null) {
                String userName = ObjectUtil.isNull(SecurityUtils.getOauthUser()) ? null : SecurityUtils.getUsername();
                this.setFieldValByName("updateBy", userName, metaObject);
            }
        }
        if (metaObject.hasGetter("updateTime")) {
            if (metaObject.getValue("updateTime") == null) {
                this.setFieldValByName("updateTime", new Date(), metaObject);
            }
        }
    }
}
